﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Windows.Forms;

namespace EscaliWeightScale
{
    class ReadScale
    {
		// Create the serial port with basic settings
		private SerialPort port = new SerialPort("COM4", 19200, Parity.None, 8, StopBits.One);

        public DateTime lastTimeUpdated = DateTime.MinValue;

        List<byte> buffer = new List<byte>();
        private List<List<byte>> linesRead = new List<List<byte>>();
        List<byte> line = new List<byte>();

        private System.Windows.Forms.Label updateLabel;

        public ReadScale(System.Windows.Forms.Label lbl)
        {
            updateLabel = lbl;
            OpenScaleConnection();
        }
        public ReadScale()
        {
            OpenScaleConnection();
        }
        public string Weight { get; set; }

		public ReadScale(string com)
		{
            port = new SerialPort(com, 9600, Parity.None, 8, StopBits.One);
			OpenScaleConnection();
		}
        private void OpenScaleConnection()
        {
			port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
			port.Open();
        }
        public void CloseScaleConnection()
        {
            port.Close();
        }
		private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
		{

            byte[] bufferByteArray = new byte[port.BytesToRead];
            port.Read(bufferByteArray, 0, port.BytesToRead);
            buffer.AddRange(bufferByteArray);

            while(buffer.Count > 11)
            {
                line = buffer.GetRange(0, 11);
                buffer = buffer.GetRange(11, buffer.Count - 11);
                if (line[line.Count - 1] == 13)
                {
                    linesRead.Add(line);
                }
            }
            if (buffer.Count == 11)
            {
                line = buffer.GetRange(0, 11);
                buffer = new List<byte>();
                if (line[line.Count - 1] == 13)
                {
                    linesRead.Add(line);
                }
                
            }
            if (line.Count == 11)
            {
                this.Weight = System.Text.ASCIIEncoding.ASCII.GetString(line.GetRange(0, 4).ToArray());
                Console.WriteLine(this.Weight);
                if (this.Weight.Contains('?') || this.Weight.Contains('\0'))
                {
                    this.Weight = this.Weight.Replace('?', '9');
                    this.Weight = this.Weight.Replace('\0', '9');
                    Console.WriteLine("AFTER REPLACE:" + this.Weight);
                }
                if ((line[9] & 0x1) == 0x1)
                {
                    try
                    {
                        float f = float.Parse(this.Weight);
                        f = f/10;
                        this.Weight = f.ToString("##0.0");
                    }
                    catch (FormatException ex)
                    {
                        Console.WriteLine("FORMAT Exception"+ex.Message + "\n\n" + ex.StackTrace);
                    }
                }
                if (updateLabel != null)
                {
                    UpdateLabel(updateLabel, this.Weight);
                }
            }
		}
        void UpdateLabel(Label lbl, String text)
        {
            if (lbl.InvokeRequired)
            { lbl.Invoke(new Action<Label, String>(UpdateLabel), new object[] { lbl, text }); }
            else
            { 
                lbl.Text = text;
                lastTimeUpdated = DateTime.Now;
            }
        }
    }
}

